//
//  DerivativeViewController.m
//  EasyToTesco
//
//  Created by mc on 16/3/7.
//  Copyright © 2016年 Jack. All rights reserved.
//

//微商专区

#import "DerivativeViewController.h"

#import "AFNetworking.h"
#import "HeaderFileForEasyToTesco.h"
#import "UIImageView+WebCache.h"

#import "SDRefresh.h"

//cell

#import "DerivativeDetailCell.h"

#import "CWStarRateView.h"

///
#import "DetailViewController.h"
//shopsdetail
#import "ShopsDetailViewController.h"

//微商城市选择
#import "DervateCityViewController.h"

#import "CityAndCountyStr.h"

@interface DerivativeViewController ()<UITableViewDataSource, UITableViewDelegate>{
    //市区
    NSString *cityStr;
    //县区
    NSString*countyStr;
    
    //页码
    NSInteger page;
}

@property (nonatomic, strong)NSMutableArray *DervateArray;
@property (nonatomic, strong)UITableView *Derivatetableview;

@property (nonatomic, strong)SDRefreshFooterView *refreshFooter;

@property (nonatomic,copy)NSString *provinceLabel;
@property (nonatomic,copy)NSString *cityLabel;
@property (nonatomic,copy)NSString *areaLabel;


@end

@implementation DerivativeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initsomething];
    //添加刷新控件
    [self setupHeader];
    [self setupFooter];
    
    //添加顶部的导航栏视图
    [self addDerivativetopView];
    
    //加载数据
    [self getweishangShopsData];
   
    
    [self addDerivativetableviewUI];
    
    
    
    
}

//实现协议，在第一个窗口显示在第二个窗口输入的值
-(void)passValue:(CityAndCountyStr *)value
{
    cityStr = value.cityName;
    countyStr = value.CountyName;
    [self getweishangShopsData];
}

- (void)initsomething {
    cityStr = @"丽水";
    countyStr = @"遂昌县";
    
    page = 1;
    
    self.DervateArray = [@[]mutableCopy];
    
    
}

- (void)addDerivativetopView {
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"微商专区";
    
    
    
    
//    UILabel *rightlabel = [[UILabel alloc] initWithFrame:CGRectMake(WEITH-120, (CGRectGetHeight(self.secondView.frame)-30)/2, 110, 30)];
//    rightlabel.text = @"微商城市选择";
//    rightlabel.textAlignment = NSTextAlignmentRight;
//    rightlabel.font = [UIFont systemFontOfSize:14];
//    [self.secondView addSubview:rightlabel];
//    
//    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    rightBtn.frame = CGRectMake(WEITH-80, 0, 80, CGRectGetHeight(self.secondView.frame));
//    [self.secondView addSubview:rightBtn];
//    [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
    

}

- (void)rightBtnClick {
    DervateCityViewController *derCity = [[DervateCityViewController alloc] init];
    
    derCity.delegate = self;
    
    [self presentViewController:derCity animated:YES completion:nil];
}

- (void)addDerivativetableviewUI {
    self.Derivatetableview = [[UITableView alloc] initWithFrame:CGRectMake(0, HIGHT*0.1, WEITH, HIGHT*0.9) style:UITableViewStylePlain];
    self.Derivatetableview.delegate = self;
    self.Derivatetableview.dataSource = self;
    
    self.Derivatetableview.tableFooterView = [[UIView alloc] init];
    self.Derivatetableview.rowHeight = 90;
    [self.view addSubview:self.Derivatetableview];
    
}


- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.DervateArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"DerivativeDetailCell";
        DerivativeDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"DerivativeDetailCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
    
    NSString *string = [NSString stringWithFormat:@"http://www.ylgw8.com/Uploads/sjpic/m_%@", [self.DervateArray[indexPath.row] objectForKey:@"sdpic"]];
    [cell.DerivatImage sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"cellpic.png"]];
    
    
    cell.DerivatTitle.text = [NSString stringWithFormat:@"%@", [self.DervateArray[indexPath.row] objectForKey:@"title"]];
    
    cell.DerivatLocation.text = [NSString stringWithFormat:@"位置:%@", [self.DervateArray[indexPath.row] objectForKey:@"county"]];
    
    cell.DerivatSth.text =[NSString stringWithFormat:@"经营:%@", [self.DervateArray[indexPath.row] objectForKey:@"zycp"]];
    
    cell.ScoreStar.scorePercent = [[NSString stringWithFormat:@"%@", [self.DervateArray[indexPath.row] objectForKey:@"score"]] floatValue];
    
    
    cell.Scorevalue.text = [NSString stringWithFormat:@"%@", [self.DervateArray[indexPath.row] objectForKey:@"score"]];
    
    
    cell.EvalueLabel.text = [NSString stringWithFormat:@"%@人评价", [self.DervateArray[indexPath.row] objectForKey:@"m"]];
    
    return cell;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark -- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    DetailViewController *detailVC = [[DetailViewController alloc] init];
    ShopsDetailViewController *shopsVc = [[ShopsDetailViewController alloc] init];
    shopsVc.shopsID = [NSString stringWithFormat:@"%@", [self.DervateArray[indexPath.row] objectForKey:@"id"]];
    [self presentViewController:shopsVc animated:YES completion:nil];
}





- (void)setupHeader{
    //添加下拉刷新对象
    SDRefreshHeaderView *refreshHeader = [SDRefreshHeaderView refreshView];
    
    //     默认是在navigationController环境下，如果不是在此环境下，请设置
    refreshHeader.isEffectedByNavigationController = NO;
    
    //加入到目标tableview上
    [refreshHeader addToScrollView:self.Derivatetableview];
    
    //添加下拉加载内容的方法
    __weak SDRefreshHeaderView *weakRefreshHeader = refreshHeader;
    __weak typeof(self) weakSelf = self;
    refreshHeader.beginRefreshingOperation = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#pragma mark -- 加载数据的方法
            [self getweishangShopsData];
            
           
            [weakSelf.Derivatetableview reloadData];
            [weakRefreshHeader endRefreshing];
        });
    };
    
    // 进入页面自动加载一次数据
    [refreshHeader autoRefreshWhenViewDidAppear];
}

- (void)setupFooter{
    SDRefreshFooterView *refreshFooter = [SDRefreshFooterView refreshView];
    refreshFooter.isEffectedByNavigationController = NO;
    [refreshFooter addToScrollView:self.Derivatetableview];
    [refreshFooter addTarget:self refreshAction:@selector(footerRefresh)];
    _refreshFooter = refreshFooter;
}


- (void)footerRefresh{
    
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#pragma mark -- 加载数据的方法
        
        [weakSelf getweishangShopsData];
        
        
        [weakSelf.Derivatetableview reloadData];
        [weakSelf.refreshFooter endRefreshing];
    });
}





//获取商家的信息
- (void)getweishangShopsData {
    

    self.provinceLabel = @"微商";
    self.cityLabel = @"微商县";
    self.areaLabel = @"";
    
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *param = @{@"city":self.provinceLabel, @"county":self.cityLabel, @"type_name":self.areaLabel, @"P":@1};
    
    [mgr POST:@"http://www.ylgw8.com/AppShop/Getshops" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        
        NSDictionary *dic = [self toArrayOrNSDictionary:responseObject];
        
        self.DervateArray = [NSMutableArray arrayWithArray:dic[@"data"]];
        
        
        NSLog(@"%@", self.DervateArray);
        
        [self.Derivatetableview reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         NSLog(@"数据请求错误原因:%@", error);
         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];

}

// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
